package check;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class Teacher_InsertScore  {
    private String id;
    public JFrame jFrame =new JFrame("登记分数");
    //滚动面板
    private JScrollPane sptable;
    //表格
    private JTable table;
    //放置按钮的面板
    private JPanel panel;
    //设置按钮
    private JButton btsave, btdelete, btadd, btflush;
    //设置默认表格格式
    private DefaultTableModel model;
    private String course;
    Connection connection;


    public Teacher_InsertScore(String id) {
        this.id=id;
        returnCourse();
        //设置表格
        model = new DefaultTableModel();
        table = new JTable(model);
        table.setForeground(Color.BLACK);                   // 字体颜色
        table.setFont(new Font(null, Font.PLAIN, 14));      // 字体样式
        table.setSelectionForeground(Color.DARK_GRAY);      // 选中后字体颜色
        table.setSelectionBackground(Color.LIGHT_GRAY);     // 选中后字体背景
        table.setGridColor(Color.GRAY);
        table.getTableHeader().setFont(new Font(null, Font.BOLD, 14));  // 设置表头名称字体样式
        table.getTableHeader().setForeground(Color.RED);                // 设置表头名称字体颜色
        table.getTableHeader().setResizingAllowed(false);               // 设置不允许手动改变列宽
        table.getTableHeader().setReorderingAllowed(false);             // 设置不允许拖动重新排序各列

        //将表格放入滚动面板中
        sptable = new JScrollPane(table);

        //将滚动面板放入主面板中部
        jFrame.add(sptable, BorderLayout.CENTER);

        btsave = new JButton("保存");
        btadd = new JButton("添加");
        btdelete = new JButton("删除");
        btflush = new JButton("刷新");


        panel = new JPanel();
        panel.add(btadd);
        panel.add(btsave);
        panel.add(btdelete);
        panel.add(btflush);



        btsave.setVisible(false);

        jFrame.add(panel, BorderLayout.SOUTH);

        //显示初始数据
        showData();

        //设置界面基本数据
        jFrame.setSize(1000, 600);
        jFrame.setLocationRelativeTo(null);
        jFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        jFrame.setVisible(true);

        //添加监听器，因为每个实现的功能不同，所以这里使用匿名内部类来实现

        btadd.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                addData();

            }
        });
        btsave.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                saveDate();
            }
        });
        btdelete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                deleteDate();
            }
        });
        btflush.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                showData();
            }
        });

    }

     void showData() {
        // TODO Auto-generated method stub


         try {
             returnCourse();
             String sql = "select id,name,score from score where course= ? ";
             DBexecute db = new DBexecute();
             connection=db.getConnection();
            //连接数据库
            db.getConnection();
            //获取返回集
            ResultSet rs = db.executeQurey(sql,course);
            //获取列名
             System.out.println(id);
             System.out.println(course);
            ResultSetMetaData rsmt = rs.getMetaData();
            //获取列数
            int count = rsmt.getColumnCount();
            //创建一个Vector集合存放列名title
            Vector<String> title = new Vector<>();
            //存放列名
            for (int i = 1; i <= count; i++) {
                title.add(rsmt.getColumnLabel(i));
            }

            //存放集合（行数据）的集合
            Vector<Vector<String>> data = new Vector();
            //判断表中有无数据
            int rowCount = 0;
            //将数据放入data中
            while (rs.next()) {
                rowCount++;
                //设置一个集合存放行数据，在放入data中
                Vector<String> rowData = new Vector<>();
                for (int i = 1; i <= count; i++) {
                    rowData.add(rs.getString(i));
                }
                data.add(rowData);
            }
            if (rowCount == 0) {
                //若行为0即数据库表中没有数据，便将title列名放入table即可
                model.setDataVector(null, title);
            } else {
                System.out.println("查询到了"+rowCount+"条数据");
                //若有数据，则将调用setDataVector将title插入data的第0列
                model.setDataVector(data, title);
            }

        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(jFrame, "系统错误！请仔细检查！");
        }

    }

    private void addData() {
        // TODO Auto-generated method stub
        int rowCount = model.getRowCount();
        int rowCount1 = table.getRowCount();
        //最好使用Object[]
        model.insertRow(rowCount, new String[]{"0", "0","0"});
        btadd.setVisible(false);
        btsave.setVisible(true);
    }

    private void saveDate() {
        // TODO Auto-generated method stub
        int rowCount = table.getRowCount() - 1;
        //获取自己填写的数据
        String id = table.getValueAt(rowCount, 0).toString();
        String name = table.getValueAt(rowCount, 1).toString();
        String score = table.getValueAt(rowCount, 2).toString();
        DBexecute db = new DBexecute();

        try {
            db.getConnection();
            String sql = "insert score values(?,?,?,?)";
            int count = db.executeUpdate(sql, new String[]{id,name,null,score},course);
            showData();
            btadd.setVisible(true);
            btsave.setVisible(false);

            if (count == 1) {
                JOptionPane.showMessageDialog(jFrame, "插入数据成功！");
            } else {
                JOptionPane.showMessageDialog(jFrame, "插入数据失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.closeAll();
        }

    }

    private void deleteDate() {
        // TODO Auto-generated method stub
        int index[] = table.getSelectedRows();

        if (index == null) {
            JOptionPane.showMessageDialog(jFrame, "请选择需要删除的数据！", "删除", JOptionPane.PLAIN_MESSAGE);
        } else {
            try {
                int k = JOptionPane.showConfirmDialog(jFrame, "是否要删除这条记录？", "删除", JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE);
                if (k == JOptionPane.YES_OPTION) {
                    DBexecute db = new DBexecute();
                    try {
                        db.getConnection();
                        String sql = "delete from score where id=?";
                        String name = table.getValueAt(index[0], 0).toString();
                        int count = db.executeDelete(sql, new String[]{name});
                        showData();

                        if (count == 1) {
                            JOptionPane.showMessageDialog(jFrame, "删除数据成功！", "成功", JOptionPane.INFORMATION_MESSAGE);

                        } else {
                            JOptionPane.showMessageDialog(jFrame, "删除数据失败！", "失败", JOptionPane.WARNING_MESSAGE);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        db.closeAll();
                    }
                }
            } catch (Exception ee) {
                JOptionPane.showMessageDialog(jFrame, "抱歉!删除数据失败!【系统异常！】", "失败:", 0);
            }
        }

    }
    public void returnCourse() {
        try {
            DBexecute db = new DBexecute();
            db.getConnection();
            String sql="select course from 老师基本信息表 where teacherid=?";
            ResultSet rs=db.executeQurey(sql,id);
            if(rs.next()){
                this.course=rs.getString(1);
            }

        } catch (Exception e) {

        }


    }
}